package com.xxc.comtrolller;

import com.xxc.entity.Clazz;
import com.xxc.service.ClazzService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.mutable.MutableFloat;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author xiangcheng
 * @version 2022/6/21 17:41
 * @since JDK8
 */
@RestController
@RequestMapping("/clazzs")
@Slf4j
public class ClazzController {
    ClazzService clazzService;
    @Value("${upload.dir}")
    private String realpath;


    @Autowired
    public void setClazzService(ClazzService clazzService) {
        this.clazzService = clazzService;
    }

    @GetMapping
    public List<Clazz> quertAll() {
        return clazzService.queryAll();
    }

    @PostMapping
    public Clazz create(String name, MultipartFile logo, Integer tagId) throws IOException {
        log.debug("班级名称:{}", name);
        log.debug("文件名称：{}", logo.getOriginalFilename());
        log.debug("标签ID：{}", tagId);
        //1. 处理文件上传
        //2. 修改文件名称
        String newFilename = UUID.randomUUID().toString().replace("-", "") + "." +
                FilenameUtils.getExtension(logo.getOriginalFilename());
        log.debug("新的文件名：{}",newFilename);
        logo.transferTo(new File(realpath, newFilename));

        //3. 保存班级信息
        Clazz clazz = new Clazz();
        clazz.setName(name);
        clazz.setTagId(tagId);
        clazz.setPath(newFilename);

        Clazz clazz1 = clazzService.insert(clazz);

        return clazz1;
    }

    @DeleteMapping("{id}")
    public void deleteClazz(@PathVariable("id")Integer id){
        clazzService.deleteById(id);
    }

    @GetMapping("{id}")
    public Clazz clazz(@PathVariable("id")Integer id){
        return clazzService.queryById(id);
    }

}
